useOptimistic is a React Hook designed to make your app feel incredibly fast by optimistically updating the UI before an asynchronous operation (like a database write or API call) actually finishes. Instead of showing a loading spinner while waiting for a server response, useOptimistic lets you immediately display what the successful outcome should look like. If the server call succeeds, the UI stays seamless. If it fails, the Hook automatically rolls back to the previous, correct state.
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);
state: the value to be returned initially and whenever no action is pending.
updateFn(currentState, optimisticValue): a function that takes the current state and the optimistic value passed to addOptimistic and returns the resulting optimistic state. It must be a pure function. updateFn takes in two parameters. The currentState and the optimisticValue. The return value will be the merged value of the currentState and optimisticValue.
optimisticState: The resulting optimistic state. It is equal to state unless an action is pending, in which case it is equal to the value returned by updateFn.
addOptimistic: addOptimistic is the dispatching function to call when you have an optimistic update. It takes one argument, optimisticValue, of any type and will call the updateFn with state and optimisticValue.